﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace ThePushCSharp
{
    public class Renderer
    {
        public GameState state;
        public Camera camera;

        //Default tile size in pixels (tiles are square)
        //The specification requests the ability to change during runtime
        public int tileSize = 64;

        public Renderer(GameState state)
        {
            this.state = state;
            this.camera = new Camera(state.map);
        }

        public void render()
        {
            drawMap();
            drawUnits();
        }

        private void drawMap()
        {
            //Synchs up with the camera's focus
            int x = camera.x;
            int y = camera.y;
            Vector2 position = new Vector2(0, 0);

            while (position.Y < state.push.screenHeight)
            {
                while (position.X < state.push.screenWidth)
                {
                    Tile tile = state.map.getTile(x, y);
                    if (tile != null)
                    {
                        state.push.spriteBatch.Draw(tile.terrain.texture, position, Color.White);

                        //Fog of War
                        if (!tile.canBeSeen())
                        {
                            state.push.spriteBatch.Draw(state.map.fogOfWar, position, Color.White);
                        }
                    }

                    position.X += tileSize;
                    x++;
                }

                //Resets the X positions to start a new row
                x = camera.x;
                y++;
                position.X = 0;
                position.Y += tileSize;
            }
        }

        private void drawUnits()
        {
            Vector2 position = new Vector2(0, 0);

            for (int x = 0; x < state.push.screenWidth / tileSize; x++)
            {
                for (int y = 0; y < state.push.screenHeight / tileSize; y++)
                {
                    Tile tile = state.map.getTile(x + camera.x, y + camera.y);
                    if (tile != null && tile.unit != null)
                    {
                        position.X = x * tileSize;
                        position.Y = y * tileSize;

                        //Draws the entire texture (no animation at this point)
                        state.push.spriteBatch.Draw(tile.unit.unitTexture, position, null, tile.unit.getColor());
                    }
                }
            }
        }
    }
}
